/**


    httpServer创建,可以再进行一次封装达到极简效果

 */

function startHttpServer() {

    let router = os.httpServer
        .createRouter()
        //设置全局的router的Responsede的的响应类型
        .setResponseHeader("content-type", "application/json")
        //指定网站目录
        .setWebRoot("www");

    //设置静态目录 静态目录是基于webRoot 所以此处的/* 不会影响restApi接口的！比如下面的test接口
    router.handler("/*", router.getStaticHandler("assest"));



    //此处的ctx需要重新单独封装,
    //handler第一个参数是接受的请求类型POST||GET 为空表示都可以,第二个参数是路由
    router.handler("post", "/test", (ctx) => {

        //ctx.params() 返回的是JSON字符串...
        let params = JSON.parse(ctx.params());

        let response = ctx.response();

        /**
         * 前面全局设置了之后，可以在此处，单独定义该路由的content-type;
         * response.putHeader("content-type","text/html");
         */

        response.end( JSON.stringify(params) );

        os.debug("OK");
    });

    router.listen(9191);
}




/**


 httpClient

 */


function httpClientGetTest() {
    var http = require('http');

    var querystring = require('querystring');

    var data = {
        a: 123,
        time: new Date().getTime()};//这是需要提交的数据


    var content = querystring.stringify(data);

    var options = {
        hostname: '127.0.0.1',
        port: 3000,
        path: '/pay/pay_callback?' + content,
        method: 'GET'
    };

    var req = http.request(options, function (res) {
        console.log('STATUS: ' + res.statusCode);
        console.log('HEADERS: ' + JSON.stringify(res.headers));
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            console.log('BODY: ' + chunk);
        });
    });

    req.on('error', function (e) {
        console.log('problem with request: ' + e.message);
    });

    req.end();
}

function httpClientPostTest() {
    var http = require('http');

    var querystring = require('querystring');

    var post_data = {
        a: 123,
        time: new Date().getTime()};//这是需要提交的数据


    var content = querystring.stringify(post_data);

    var options = {
        hostname: '127.0.0.1',
        port: 3000,
        path: '/pay/pay_callback',
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
    };

    var req = http.request(options, function (res) {
        console.log('STATUS: ' + res.statusCode);
        console.log('HEADERS: ' + JSON.stringify(res.headers));
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            console.log('BODY: ' + chunk);
            //JSON.parse(chunk)
        });
    });

    req.on('error', function (e) {
        console.log('problem with request: ' + e.message);
    });

// write data to request body
    req.write(content);

    req.end();
}
